#include "Comm.hpp"

int main()
{
    // 1. 客户端只需要获取服务端创建的共享内存即可
    key_t k = ftok(PATH_NAME, PROJ_ID);
    if(k == -1)
    {
        Log("create key fail", Error) << "client key: " << TransToHex(k) << endl;
        exit(1);
    }
    Log("create key done", Debug) << "client key: " << TransToHex(k) << endl;


    // 2. 获取共享内存
    int shmid = shmget(k, SHM_SIZE, 0);
    if(shmid == -1)
    {
        Log("create shm fail", Error) << "client key: " << TransToHex(k) << endl;
        exit(2);
    }
    Log("create shm done", Debug) << "client key: " << TransToHex(k) << endl;

    // 3. 挂接共享内存
    char* shmaddr = (char*)shmat(shmid, nullptr, 0);
    if(shmaddr == (char*)-1)
    {
        Log("attach shm failed", Error) << " client key : " << TransToHex(k) << endl;
        exit(3);
    }
    Log("attach shm success", Debug) << " client key : " << TransToHex(k) << endl;

    // 客户端以写方式打开管道文件
    int fd = OpenFIFO(FIFO_NAME, WRITE);

    // 4. 使用,客户端将共享内存看做一个char类型的buffer
    while(true)
    {
        ssize_t s = read(0, shmaddr, SHM_SIZE - 1);
        if(s > 0)
        {
            // 临界区
            shmaddr[s - 1] = '\0';  // 清除'\n'
            Signal(fd); // 客户端唤醒服务端
            if(strcmp(shmaddr, "quit") == 0) break;
        }
    }

    // 以下代码是自动向共享内存中写入数据
    // char a = 'a';
    // for(; a <= 'z'; a++)
    // {
    //     // shmaddr[a-'a'] = a;
    //     // 我们是每一次都向shmaddr[共享内存的起始地址]写入
    //     // snprintf(shmaddr, SHM_SIZE - 1, "hello server, 我是其他进程,我的pid: %d, inc: %c\n", getpid(), a);
    //     // sleep(5);
    // }

    // strcpy(shmaddr, "quit");

    // 5. 去关联
    int n = shmdt(shmaddr);
    assert(n != -1);
    Log("detach shm done", Debug) << "client key: " << TransToHex(k) << endl;

    // 客户端不需要删除共享内存！

    return 0;
}